<template>
  <div class="page-container">
    <div class="left_container">
      <dv-border-box-8 class="left_container_top">
        <div class="left_container_top_title"></div>
        <div
          class="left_container_top_container"
          ref="chartDom1"
          style="width: 100%; height: 100%; margin: 0 auto"
        ></div>
      </dv-border-box-8>
      <dv-border-box-8 class="left_container_bottom">
        <div class="left_container_bottom_title"></div>
        <div class="left_container_bottom_container" ref="chartDom2"></div>
      </dv-border-box-8>
    </div>
    <div class="center_container">
      <div class="center_container_top">
        <div
          ref="charts"
          style="
            width: 100%;
            height: 100%;
            margin: 0 auto;
            border: 1px solid cyan;
          "
        >
          <CenterMapView :mapData="mapData" />
        </div>
      </div>
      <div class="center_container_bottom">
        <dv-scroll-board :config="config" style="width: 600px; height: 350px" />
      </div>
    </div>
    <div class="right_container">
      <div class="right_container_top">
        <el-button @click="changeDepartment(1)">设计</el-button>
        <el-button @click="changeDepartment(2)">开发</el-button>
        <el-button @click="changeDepartment(3)">元宇宙</el-button>
        <div
          class="right_container_top_container"
          ref="rightEhartDom"
          style="width: 100%; height: 100%; margin: 0 auto"
        ></div>
      </div>
      <div class="right_container_bottom">
        <div class="right_container_bottom_container" ref="rightBottom"></div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
/**
 * 模块引入
 */
// import { getStatsStatus } from "@api/intelligence";
import {
  getStatsStatus,
  getStudentByAreaCode,
  getStudentDistribution,
  getStudentSalary,
} from "../../api/intelligence";
import {
  reactive,
  ref,
  onMounted,
  onUnmounted,
  nextTick,
  getCurrentInstance,
  onBeforeUnmount,
} from "vue";
import * as echarts from "echarts";
import {
  leftBottomOption,
  leftTopOption,
  rightBottomOption,
} from "./chartOption";
import { debounce } from "../../utils";
import CenterMapView from "./components/CenterMapView.vue";
import chinaCity from "../../assets/json/citylatlng.json";
import allCityData from "../../assets/json/CityData.json";
// import allCityData from "../../assets/json/citylatlng.json";
const chartDom1 = ref(null);
const chartDom2 = ref(null);
const rightEhartDom = ref(null);
const rightBottom = ref(null);
let chartInstance: any = null;
let LeftTopchartInstance: any = null;
let rightTopchartInstance: any = null;
let rightBottomchartInstance: any = null;

const mapData = ref({
  pointsData: [],
  linesData: [],
});
const config = reactive({
  data: [
    ["郝淇锋", "14k", "山西"],
    ["陈道闯", "12k", "河南"],
    ["高庆杰", "15k", "河北"],
    ["郭强", "15k", "江西"],
    ["王秦超", "14k", "山西"],
    ["王恩泽", "12k", "黑龙江"],
    ["崔宇航", "14k", "河南"],
    ["刘怡鹏", "12k", "山西"],
    ["王旭昊", "13k", "河南"],
    ["温明阳", "12k", "河北"],
  ],
});
let CenterMapcharts = null;
// 初始化ECharts实例并设置配置项（这里以折线图为例，但可灵活替换）
onMounted(async () => {
  // await nextTick(); // 确保DOM已经渲染完成
  chartInstance = echarts.init(chartDom2.value);
  LeftTopchartInstance = echarts.init(chartDom1.value);
  rightTopchartInstance = echarts.init(rightEhartDom.value);
  rightBottomchartInstance = echarts.init(rightBottom.value);
  LeftTopchartInstance.setOption(leftTopOption);

  rightBottomchartInstance.setOption(rightBottomOption);
});

// 销毁ECharts实例
onUnmounted(() => {
  if (chartInstance != null && chartInstance.dispose) {
    chartInstance.dispose();
    LeftTopchartInstance.dispose();
  }
});

const getStatsStatusFn = async () => {
  const result = await getStatsStatus({});
  console.log("result", result);
  let seriesData = result.data.result.map((item) => {
    return {
      value: item.total,
      name: filterName(item.status),
    };
  });
  const option = leftBottomOption;
  option.series[0].data = seriesData;
  chartInstance.setOption(option);
  const leftTopResult = await getStudentByAreaCode();
  // console.log(leftTopResult, "-----");
  const resultData = transformArray(leftTopResult.data.result);
  // console.log("resultData", resultData);
  let yAxisData = [];
  let series1Data = [];
  let series2Data = [];
  let series3Data = [];
  for (let key in resultData) {
    // console.log(key, CityCodyToName(key), "====");
    yAxisData.push(CityCodyToName(key));
    series1Data.push(resultData[key][0]);
    series2Data.push(resultData[key][1]);
    series3Data.push(resultData[key][2]);
  }
  // console.log("yAxisData", yAxisData);
  // console.log("series1Data", series1Data);
  // console.log("series2Data", series2Data);
  // console.log("series3Data", series3Data);
  const leftOption = leftTopOption;
  leftOption.yAxis.data = yAxisData;
  leftOption.series[0].data = series1Data;
  leftOption.series[1].data = series2Data;
  leftOption.series[2].data = series3Data;
  LeftTopchartInstance.setOption(leftOption);
};
// 遍历数组，根据workCity和gradYear对total进行分组
function transformArray(array) {
  // console.log(array, "11111111111");
  const result = {};
  array.forEach((item) => {
    const { workCity, gradYear, total } = item;
    if (!result[workCity]) {
      result[workCity] = [];
    }
    result[workCity].push({ gradYear, total });
  });

  // 对每个workCity的数组进行gradYear降序排序，并仅保留total值
  for (let city in result) {
    result[city] = result[city]
      .sort((a, b) => b.gradYear - a.gradYear)
      .map((item) => item.total);
  }

  // 确定最长数组的长度
  const maxLength = Math.max(...Object.values(result).map((arr) => arr.length));

  // 对长度不足的数组进行0的填充
  for (let city in result) {
    while (result[city].length < maxLength) {
      result[city].unshift(0); // 在数组开头插入0
    }
  }
  return result;
}
function CityCodyToName(code, CityData = allCityData) {
  // console.log("CityData", CityData, code);
  let label = "未知";
  for (let i = 0; i < CityData.length; i++) {
    if (CityData[i].code == code) {
      return (label = CityData[i].label);
    } else if (
      CityData[i].code.startsWith(code.slice(0, 2)) &&
      CityData[i].children &&
      CityData[i].children.length > 0
    ) {
      // 有子元素
      label = CityCodyToName(code, CityData[i].children);
      if (label !== "未知") {
        return label;
      }
    }
    // console.log(":label", label);
  }
}

const changeDepartment = function (partId) {
  getEchartsMapData(partId);
};
async function getEchartsMapData(partId = 1) {
  let MapResult = await getStudentDistribution({ expertiseId: partId });
  interface RightTopchartDataItem {
    name: string;

    value?: number;
  }
  let RightTopchartData: RightTopchartDataItem[] = [];
  let RightTopchartYaxData: string[] = [];
  const opt = {
    index: 0,
  };
  const getArrByKey = (data, k) => {
    let key = k || "value";
    let res = [];
    if (data) {
      data.forEach(function (t) {
        res.push(t[key]);
      });
    }
    return res;
  };
  const backColor = ["#FC619D", "#FF904D", "#48BFE3"];
  const data = RightTopchartData;
  data.sort((a, b) => {
    return b.value - a.value;
  });
  let rightOption = {
    grid: {
      top: "2%",
      bottom: -15,
      right: 30,
      left: -30,
      containLabel: true,
    },
    xAxis: {
      show: false,
    },
    yAxis: [
      {
        triggerEvent: true,
        show: true,
        inverse: true,
        data: ["南京"],
        axisLine: {
          show: false,
        },
        splitLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          interval: 0,
          color: "#666",
          align: "left",
          margin: 20,
          fontSize: 13,
          formatter: function (name, index) {
            // console.log(value, index, "====", data);
            return data[index].name;
          },
          rich: {
            idx0: {
              color: "#FB375E",
              backgroundColor: "#FFE8EC",
              borderRadius: 100,
              padding: [5, 8],
            },
            idx1: {
              color: "#FF9023",
              backgroundColor: "#FFEACF",
              borderRadius: 100,
              padding: [5, 8],
            },
            idx2: {
              color: "#01B599",
              backgroundColor: "#E1F7F3",
              borderRadius: 100,
              padding: [5, 8],
            },
            idx: {
              color: "#333",
              borderRadius: 100,
              padding: [5, 8],
            },
            title: {
              width: 165,
            },
          },
        },
      },
      {
        triggerEvent: true,
        show: true,
        inverse: true,
        data: getArrByKey(data, "name"),
        axisLine: {
          show: false,
        },
        splitLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          interval: 0,
          color: "#666",
          align: "left",
          margin: 20,
          fontSize: 13,
          formatter: function (value, index) {
            console.log(value, index, "====", data);
            return "学生人数：" + data[index].value;
          },
          // formatter: function (value, index) {
          //   return "学生人数：" + value;
          // },
        },
      },
    ],
    series: [
      {
        name: "条",
        type: "bar",
        yAxisIndex: 0,
        data: [],
        barWidth: 10,
        itemStyle: {
          color: (val) => {
            if (val.dataIndex < 3 && opt.index === 0) {
              return backColor[val.dataIndex];
            } else {
              return "#1990FF";
            }
          },
          barBorderRadius: 30,
        },
      },
    ],
  };
  MapResult = mergeCityData(MapResult.data.result, chinaCity);
  console.log("MapResult", MapResult);
  MapResult.forEach((item) => {
    const { name, latlng } = item;
    // console.log(item);
    // console.log("item.latIng", latlng);
    let pointItem = {
      name: name,
      value: latlng.split(",").reverse(),
      itemStyle: { color: "#00EEFF" },
    };
    let lineItem = {
      coords: [[117.210966, 39.1397], latlng.split(",").reverse()],
    };
    mapData.value.pointsData.push(pointItem);
    mapData.value.linesData.push(lineItem);
    RightTopchartData.push({ name: name, value: item.total });
    RightTopchartYaxData.push(name);
    rightTopchartInstance.setOption(rightOption);
    // console.log("name", name, item.total);
  });

  console.log("rightOption", rightOption);
  rightOption.yAxis[0].data = RightTopchartYaxData;
  rightOption.yAxis[1].data = RightTopchartYaxData;
  // console.log("rightTopchartInstance", rightTopchartInstance);
  // console.log("RightTopchartData", RightTopchartData);
  rightOption.series[0].data = RightTopchartData;
  rightTopchartInstance.setOption(rightOption);

  function mergeCityData(arr, allCityData) {
    // 创建一个映射对象，用于快速查找城市信息
    const cityMap = {};
    allCityData.forEach((city) => {
      cityMap[city.no.slice(0, 4)] = {
        // 假设 workCity 是 no 的前4位
        latlng: city.latlng,
        name: city.name,
      };
    });

    // 遍历 arr 数组，并构建新的数组
    const result = [];
    arr.forEach((item) => {
      const cityInfo = cityMap[item.workCity];
      if (cityInfo) {
        // 如果存在城市信息，则创建一个新对象并添加到结果数组中
        result.push({
          ...cityInfo, // 添加 latlng 和 name
          total: item.total, // 添加 total
          // 注意：这里没有添加 workCity，因为它已经通过 name 表示了。
          // 如果你确实需要 workCity 字段，可以像这样添加：
          // workCity: cityInfo.name.replace(/\s+/g, '').toLowerCase(), // 转换为无空格小写（可选）
          // 但通常我们不会这样做，因为 name 已经足够表示城市了。
        });
      }
    });

    return result;
  }
}

function rightBottomOptionFn() {
  getStudentSalary().then((res) => {
    let result = res.data.result;
    const resultData = getSalaryDistribution(result);
    console.log("resultData", resultData);
    rightBottomOption.series[0].data = resultData;
    rightBottomchartInstance.setOption(rightBottomOption);
  });
}
function getSalaryDistribution(arr) {
  // 定义区间和对应的名称
  const intervals = [
    { name: "30k以上", min: 30000 },
    { name: "20k-25k", min: 20000, max: 25000 },
    { name: "15k-20k", min: 15000, max: 20000 },
    { name: "10k-15k", min: 10000, max: 15000 },
    { name: "10k以下", max: 10000 },
  ];

  // 初始化区间统计对象
  const distribution = intervals.map((interval) => ({
    name: interval.name,
    value: 0,
  }));

  // 遍历数组并累加total到相应的区间
  arr.forEach((item) => {
    const salary = item.salary;
    for (let interval of intervals) {
      if (
        (interval.min &&
          salary >= interval.min &&
          (!interval.max || salary < interval.max)) ||
        (!interval.min && salary < interval.max)
      ) {
        distribution[intervals.indexOf(interval)].value += item.total;
        break;
      }
    }
  });

  return distribution;
}
//防抖函数
const $_resizeHandler = debounce(() => {
  console.log("resize");
  chartInstance.resize();
  LeftTopchartInstance.resize();
  rightTopchartInstance.resize();
  rightBottomchartInstance.resize();
}, 200);
// 为了让echarts随着屏幕大小变化
window.addEventListener("resize", $_resizeHandler);
onBeforeUnmount(() => {
  window.removeEventListener("resize", $_resizeHandler);
});
const filterName = function (name: string) {
  switch (name) {
    case "1":
      return "待毕业";
    case "2":
      return "已毕业";
    case "3":
      return "就业";
    case "4":
      return "未就业";
    case "5":
      return "返校重听";
  }
};
getStatsStatusFn();
getEchartsMapData();
rightBottomOptionFn();
</script>
<style lang="scss" scoped>
.page-container {
  position: absolute;
  z-index: 12;
  width: 100%;
  height: 100%;
  border: 3px solid red;
  display: flex;
  .left_container,
  .right_container {
    width: 450px;
    height: 881px;
    display: flex;
    flex-direction: column;
    &_top {
      width: 100%;
      height: 554px;
      // background-color: pink;
      &_title {
      }
      &_container {
      }
    }
    &_bottom {
      flex: 1;
      margin-top: 25px;
      &_title {
        background: url("../../assets/images/Photo／背景／标题 左@2x.png");
        background-size: 100% 100%;
        height: 42px;
        width: 100%;
        margin-top: 11px;
      }
      &_container {
        width: 100%;
        height: 249px;
        background: rgb(2, 2, 92);
      }
    }
  }
  .center_container {
    width: 720px;
    height: 456px;
    border: 1px solid red;
    margin-left: 89px;
    .center_container_top {
      border: 1px solid greenyellow;
      width: 100%;
      height: 100%;
    }
  }
  .right_container {
    .right_container_bottom {
      height: 450px;
    }
  }
}
</style>
